<template>
  <MainLayout>
    <div class="product-list-content">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><a href="/">首页</a></el-breadcrumb-item>
        <el-breadcrumb-item>{{ currentCategory }}</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="content-body">
        <!-- 分类切换标签 -->
        <div class="category-tabs-bar">
          <button 
            v-for="cat in allCategories" 
            :key="cat.key"
            :class="['category-tab', { active: route.params.category === cat.key || (route.params.category === undefined && cat.key === 'all') }]"
            @click="switchCategory(cat.key)"
          >
            {{ cat.name }}
          </button>
        </div>

        <div class="filter-bar">
          <el-select v-model="sortBy" placeholder="排序" style="width: 150px">
            <el-option label="价格从低到高" value="price-asc"></el-option>
            <el-option label="价格从高到低" value="price-desc"></el-option>
          </el-select>
        </div>

        <el-row :gutter="20">
          <el-col :span="6" v-for="product in filteredProducts" :key="product.id">
            <el-card :body-style="{ padding: '0' }" shadow="hover" class="product-card" @click="goToProduct(product.id)">
              <img :src="product.image" class="product-image" />
              <div style="padding: 14px;">
                <h4>{{ product.name }}</h4>
                <p class="product-price">¥{{ product.price }}</p>
                <el-button type="primary" size="small" @click.stop="addToCart(product)">加入购物车</el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-empty v-if="filteredProducts.length === 0" description="暂无商品" />
      </div>
    </div>
  </MainLayout>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { productAPI } from '../api'
import { ElMessage } from 'element-plus'
import MainLayout from '../layouts/MainLayout.vue'

const route = useRoute()
const router = useRouter()

const categoryMap = {
  'makeup': { name: '美妆', icon: '💄' },
  'clothing': { name: '服饰', icon: '👗' },
  'digital': { name: '数码', icon: '📱' },
  'appliance': { name: '电器', icon: '🔌' },
  'fresh': { name: '生鲜', icon: '🍎' },
  'outdoor': { name: '户外', icon: '🏕️' }
}

const allCategories = [
  { key: 'all', name: 'ALL' },
  { key: 'makeup', name: '美妆' },
  { key: 'clothing', name: '服饰' },
  { key: 'digital', name: '数码' },
  { key: 'appliance', name: '电器' },
  { key: 'fresh', name: '生鲜' },
  { key: 'outdoor', name: '户外' }
]

const currentCategory = computed(() => categoryMap[route.params.category]?.name || '全部商品')

const switchCategory = (categoryKey) => {
  if (categoryKey === 'all') {
    router.push('/')
  } else {
    router.push(`/category/${categoryKey}`)
  }
}

const products = ref([])
const sortBy = ref('price-asc')

const filteredProducts = computed(() => {
  let filtered = products.value

  // 检查URL参数中的搜索关键词
  const searchKeyword = route.query.search || ''
  if (searchKeyword) {
    filtered = filtered.filter(p => 
      p.name.includes(searchKeyword) || 
      p.description?.includes(searchKeyword)
    )
  }

  if (sortBy.value === 'price-asc') {
    filtered = [...filtered].sort((a, b) => a.price - b.price)
  } else if (sortBy.value === 'price-desc') {
    filtered = [...filtered].sort((a, b) => b.price - a.price)
  }

  return filtered
})

const fetchProducts = async () => {
  try {
    const category = route.params.category
    const response = await productAPI.getProducts(category)
    // 由于响应拦截器已经返回 response.data，所以直接使用
    products.value = response || []
    
    if (products.value.length === 0) {
      ElMessage.info('该分类下暂无商品')
    }
  } catch (error) {
    console.error('获取商品失败:', error)
    ElMessage.error('获取商品失败，请检查服务器是否运行')
    products.value = []
  }
}

const goToProduct = (id) => {
  router.push(`/product/${id}`)
}

const addToCart = (product) => {
  const savedCart = localStorage.getItem('cart')
  let cartItems = savedCart ? JSON.parse(savedCart) : []
  
  // 检查是否已存在
  const existingItem = cartItems.find(item => item.id === product.id)
  if (existingItem) {
    existingItem.quantity += 1
  } else {
    cartItems.push({ ...product, quantity: 1 })
  }
  
  localStorage.setItem('cart', JSON.stringify(cartItems))
  ElMessage.success('已添加到购物车')
}

onMounted(() => {
  fetchProducts()
})

watch(() => route.params.category, () => {
  fetchProducts()
})
</script>

<style scoped>
.product-list-content {
  width: 100%;
  max-width: 100%;
  padding: 0;
  box-sizing: border-box;
}

.content-body {
  margin-top: 40px;
}

.category-tabs-bar {
  display: flex;
  gap: 40px;
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e8e8e8;
}

.category-tab {
  background: none;
  border: none;
  padding: 0;
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 1px;
  color: #666666;
  cursor: pointer;
  position: relative;
  transition: color 0.3s ease;
}

.category-tab:hover {
  color: #000000;
}

.category-tab.active {
  color: #000000;
  font-weight: 400;
}

.category-tab.active::after {
  content: '';
  position: absolute;
  bottom: -21px;
  left: 0;
  right: 0;
  height: 1px;
  background: #000000;
}

.filter-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  justify-content: flex-end;
}

.product-card {
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 0;
  overflow: hidden;
}

.product-card:hover {
  border-color: #000000;
}

.product-image {
  width: 100%;
  height: 300px;
  object-fit: cover;
}

.product-price {
  color: #000000;
  font-size: 16px;
  font-weight: 400;
  margin: 10px 0;
  letter-spacing: 1px;
}
</style>

